package ee.ut.cs.mc.mad.a72041.ha1;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ee.ut.cs.mc.mad.a72041.R;

/**
 * Implementation for home assignment 1
 * 
 * @author Kaarel Jõgeva
 */
public class ContactMailerActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_mailer);
        ListView contactsList = (ListView) findViewById(R.id.contactsListView);
        ContactAdapter adapter = new ContactAdapter(getApplication(), R.layout.view_contact, getContacts());
        contactsList.setAdapter(adapter);
    }

    private List<Contact> getContacts() {
        List<Contact> contacts = new ArrayList<Contact>();

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                int idIdx = cur.getColumnIndex(ContactsContract.Contacts._ID);
                String id = idIdx > -1 ? cur.getString(idIdx) : null;
                int nameIdx = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                String name = nameIdx > -1 ? cur.getString(nameIdx) : null;
                Contact c = new Contact(name);

                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[] { id }, null);
                    if (pCur.getCount() > 0) {
                        while (pCur.moveToNext()) {
                            int numberIdx = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                            String number = numberIdx > -1 ? pCur.getString(numberIdx) : null;
                            c.setPhone(number);
                            break;
                        }
                    }
                    pCur.close();
                }

                Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                        new String[] { id }, null);
                if (emailCur.getCount() > 0) {
                    while (emailCur.moveToNext()) {
                        // This would allow you get several email addresses
                        // if the email addresses were stored in an array
                        int emailIdx = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
                        String email = emailIdx > -1 ? emailCur.getString(emailIdx) : null;
                        c.setEmail(email);
                        break;
                    }
                }
                emailCur.close();
                contacts.add(c);
            }
        }
        cur.close();

        return contacts;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_contact_mailer, menu);
        return true;
    }

    /**
     * Adapter for contacts list
     * 
     * @author Kaarel Jõgeva
     */
    private class ContactAdapter extends ArrayAdapter<Contact> {

        private final List<Contact> contacts;

        public ContactAdapter(Context context, int textViewResourceId, List<Contact> objects) {
            super(context, textViewResourceId, objects);
            contacts = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.view_contact, null);
            }
            Contact c = contacts.get(position);
            if (c != null) {
                TextView name = (TextView) v.findViewById(R.id.contactName);
                name.setText(c.getName());
                TextView id = (TextView) v.findViewById(R.id.contactPos);
                id.setText(Integer.toString(position + 1));

                v.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        sendEmail(v);

                    }
                });
            }

            return v;
        }

        public void sendEmail(View view) {
            String contactPos = ((TextView) view.findViewById(R.id.contactPos)).getText().toString();
            Contact contact = contacts.get((Integer.parseInt(contactPos) - 1));
            if (contact.getEmail() == null) {
                Toast.makeText(getApplication(), getString(R.string.error_no_email), Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("message/rfc822");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { contact.getEmail() });
            try {
                // would prefer startActivityForResult but it seems that native e-mail clients don't return results... :(
                startActivity(Intent.createChooser(intent, getString(R.string.choose_email_client)));
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getApplicationContext(), getString(R.string.no_email_clients), Toast.LENGTH_SHORT).show();
                return;
            }

            TextView tvContact = (TextView) findViewById(R.id.selectedContact);
            tvContact.setText(getString(R.string.sent_email_info, contact.getName(), contact.getPhone(), contact.getEmail()));

        }

    }

}
